<template>
  <el-dialog
    v-model="visible"
    :title="isEdit ? '编辑场景' : '新增场景'"
    width="900px"
    :close-on-click-modal="false"
    top="5vh"
    @closed="handleClosed"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      class="scene-form"
    >
      <!-- 基本信息 -->
      <el-divider content-position="left">基本信息</el-divider>

      <el-form-item label="场景名称" prop="scene_name">
        <el-input
          v-model="formData.scene_name"
          placeholder="请输入场景名称（1-50字符）"
          maxlength="50"
          :disabled="isEdit && isBuiltin"
          show-word-limit
        />
        <div class="form-hint" v-if="isEdit && isBuiltin">
          💡 内置场景不允许修改名称
        </div>
      </el-form-item>

      <el-form-item label="场景描述" prop="description">
        <el-input
          v-model="formData.description"
          type="textarea"
          :rows="3"
          placeholder="请输入场景描述（可选，最长200字符）"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>

      <!-- 关键词配置 -->
      <el-divider content-position="left">关键词配置</el-divider>

      <el-form-item label="主关键词" prop="main_keywords">
        <el-select
          v-model="formData.main_keywords"
          multiple
          filterable
          allow-create
          default-first-option
          :loading="loadingKeywords"
          placeholder="请输入主关键词，至少1个（支持创建新关键词）"
          style="width: 100%"
          @focus="loadKeywords"
          @visible-change="(visible) => visible && loadKeywords()"
        >
          <el-option
            v-for="keyword in keywordOptions"
            :key="keyword"
            :label="keyword"
            :value="keyword"
          />
        </el-select>
        <div class="form-hint">
          💡 主关键词是场景匹配的核心，至少需要1个，每个关键词1-50字符
        </div>
      </el-form-item>

      <el-form-item label="辅助关键词" prop="aux_keywords">
        <el-select
          v-model="formData.aux_keywords"
          multiple
          filterable
          allow-create
          default-first-option
          :loading="loadingKeywords"
          placeholder="请输入辅助关键词（可选，支持创建新关键词）"
          style="width: 100%"
          @focus="loadKeywords"
          @visible-change="(visible) => visible && loadKeywords()"
        >
          <el-option
            v-for="keyword in keywordOptions"
            :key="keyword"
            :label="keyword"
            :value="keyword"
          />
        </el-select>
        <div class="form-hint">
          💡 辅助关键词用于增强匹配精度，可选，每个关键词1-50字符
        </div>
      </el-form-item>

      <!-- 场景特性 -->
      <el-divider content-position="left">场景特性</el-divider>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="分类" prop="category">
            <el-input
              v-model="formData.category"
              placeholder="请输入分类（可选）"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="优先级" prop="priority_level">
            <el-select
              v-model="formData.priority_level"
              placeholder="请选择优先级"
              style="width: 100%"
            >
              <el-option label="低" value="low" />
              <el-option label="中" value="medium" />
              <el-option label="高" value="high" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="标签" prop="tags">
        <el-select
          v-model="formData.tags"
          multiple
          filterable
          allow-create
          default-first-option
          placeholder="请输入标签（可选，支持创建新标签）"
          style="width: 100%"
        >
        </el-select>
      </el-form-item>

      <!-- 责任与动作 -->
      <el-divider content-position="left">责任与动作</el-divider>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="责任部门" prop="responsible_department">
            <el-select
              v-model="formData.responsible_department"
              placeholder="请选择责任部门（可选）"
              clearable
              filterable
              style="width: 100%"
            >
              <el-option
                v-for="dept in props.departmentOptions || []"
                :key="dept.value"
                :label="dept.label"
                :value="dept.value"
            />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="默认动作" prop="default_action">
            <el-select
              v-model="formData.default_action"
              placeholder="请选择默认动作"
              style="width: 100%"
            >
              <el-option label="审核" value="review" />
              <el-option label="告警" value="alert" />
              <el-option label="工单" value="ticket" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 高级配置 -->
      <el-divider content-position="left">高级配置（可选）</el-divider>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="自动清理">
            <el-switch v-model="formData.config.auto_cleanup" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="保留天数">
            <el-input-number
              v-model="formData.config.retention_days"
              :min="1"
              :max="365"
              placeholder="保留天数"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="启用缓存">
            <el-switch v-model="formData.config.cache_enabled" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最大结果数">
            <el-input-number
              v-model="formData.config.max_results"
              :min="1"
              :max="10000"
              placeholder="最大结果数"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="搜索超时（秒）">
        <el-input-number
          v-model="formData.config.search_timeout"
          :min="1"
          :max="600"
          placeholder="搜索超时时间"
          style="width: 100%"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSave" :loading="saving">
        保存
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from "vue";
import { ElMessage, ElForm } from "element-plus";
import type { FormRules } from "element-plus";
import { getSceneKeywords } from "../../../servers";

// 定义props
const props = defineProps({
  modelValue: { type: Boolean, default: false },
  sceneDetail: {
    type: Object,
    default: () => null,
  },
  isEdit: { type: Boolean, default: false },
  departmentOptions: {
    type: Array as () => Array<{ label: string; value: string }>,
    default: () => [],
  },
});

// 定义emits
const emit = defineEmits<{
  (e: "update:modelValue", value: boolean): void;
  (e: "save", data: any): void;
}>();

// visible computed 属性
const visible = computed({
  get: () => props.modelValue,
  set: (value: boolean) => emit("update:modelValue", value),
});

// 表单引用
const formRef = ref<InstanceType<typeof ElForm>>();
const saving = ref(false);

// 关键词选项列表
const keywordOptions = ref<string[]>([]);
const loadingKeywords = ref(false);
const keywordCache = ref<Map<string, string[]>>(new Map()); // 缓存搜索结果

// 判断是否为内置场景
const isBuiltin = computed(() => {
  return props.sceneDetail?.is_builtin || false;
});

// 表单数据
const formData = reactive({
  scene_name: "",
  description: "",
  main_keywords: [] as string[],
  aux_keywords: [] as string[],
  category: "",
  tags: [] as string[],
  priority_level: "medium" as "low" | "medium" | "high",
  responsible_department: "",
  default_action: "review" as "review" | "alert" | "ticket",
  config: {
    auto_cleanup: false,
    retention_days: 60,
    cache_enabled: true,
    max_results: 500,
    search_timeout: 180,
  },
});

// 表单验证规则
const formRules: FormRules = {
  scene_name: [
    { required: true, message: "请输入场景名称", trigger: "blur" },
    {
      min: 1,
      max: 50,
      message: "场景名称长度应在1-50个字符之间",
      trigger: "blur",
    },
  ],
  main_keywords: [
    { required: true, message: "请输入至少1个主关键词", trigger: "change" },
    {
      validator: (rule, value, callback) => {
        if (!value || value.length === 0) {
          callback(new Error("请输入至少1个主关键词"));
        } else {
          const invalidKeywords = value.filter(
            (keyword: string) =>
              !keyword || keyword.length < 1 || keyword.length > 50
          );
          if (invalidKeywords.length > 0) {
            callback(new Error("每个主关键词长度应在1-50个字符之间"));
          } else {
            callback();
          }
        }
      },
      trigger: "change",
    },
  ],
  aux_keywords: [
    {
      validator: (rule, value, callback) => {
        if (value && value.length > 0) {
          const invalidKeywords = value.filter(
            (keyword: string) =>
              !keyword || keyword.length < 1 || keyword.length > 50
          );
          if (invalidKeywords.length > 0) {
            callback(new Error("每个辅助关键词长度应在1-50个字符之间"));
          } else {
            callback();
          }
        } else {
          callback();
        }
      },
      trigger: "change",
    },
  ],
  priority_level: [
    {
      validator: (rule, value, callback) => {
        if (value && !["low", "medium", "high"].includes(value)) {
          callback(new Error("优先级只能是 low/medium/high"));
        } else {
          callback();
        }
      },
      trigger: "change",
    },
  ],
  default_action: [
    {
      validator: (rule, value, callback) => {
        if (value && !["review", "alert", "ticket"].includes(value)) {
          callback(new Error("默认动作只能是 review/alert/ticket"));
        } else {
          callback();
        }
      },
      trigger: "change",
    },
  ],
};

// 加载关键词库
const loadKeywords = async (searchKeyword?: string) => {
  // 如果有缓存，直接使用缓存
  const cacheKey = searchKeyword || "all";
  if (keywordCache.value.has(cacheKey) && !searchKeyword) {
    keywordOptions.value = keywordCache.value.get(cacheKey) || [];
    return;
  }

  try {
    loadingKeywords.value = true;
    const res = await getSceneKeywords({
      keyword: searchKeyword, // 搜索关键词
      per_page: 100, // 获取前100个关键词
    });

    // 从场景数据中提取所有关键词
    // 数据结构: { code: 2000, data: { scenes: [...], total: 5 } }
    const scenes = res.data?.scenes || [];

    // 收集所有场景的关键词（all_keywords, main_keywords, aux_keywords）
    const allKeywordsSet = new Set<string>();

    scenes.forEach((scene: any) => {
      // 收集 all_keywords
      if (Array.isArray(scene.all_keywords)) {
        scene.all_keywords.forEach((kw: string) => {
          if (kw && typeof kw === "string") {
            allKeywordsSet.add(kw);
          }
        });
      }
      // 收集 main_keywords
      if (Array.isArray(scene.main_keywords)) {
        scene.main_keywords.forEach((kw: string) => {
          if (kw && typeof kw === "string") {
            allKeywordsSet.add(kw);
          }
        });
      }
      // 收集 aux_keywords
      if (Array.isArray(scene.aux_keywords)) {
        scene.aux_keywords.forEach((kw: string) => {
          if (kw && typeof kw === "string") {
            allKeywordsSet.add(kw);
          }
        });
      }
    });

    // 转换为数组并排序
    let keywords = Array.from(allKeywordsSet).sort();

    // 如果有搜索关键词，进行过滤
    if (searchKeyword) {
      const searchLower = searchKeyword.toLowerCase();
      keywords = keywords.filter((kw) =>
        kw.toLowerCase().includes(searchLower)
      );
    }

    keywordOptions.value = keywords;

    // 缓存结果（只缓存全部关键词，不缓存搜索结果）
    if (!searchKeyword) {
      keywordCache.value.set("all", keywords);
    }
  } catch (error) {
    console.error("获取关键词库失败:", error);
  } finally {
    loadingKeywords.value = false;
  }
};

// 监听弹窗打开，初始化表单数据
watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      // 弹窗打开时加载关键词库
      loadKeywords();

      if (props.isEdit && props.sceneDetail) {
        // 编辑模式：填充表单
        const detail = props.sceneDetail;
        formData.scene_name = detail.scene_name || "";
        formData.description = detail.description || "";
        formData.main_keywords = detail.main_keywords || [];
        formData.aux_keywords = detail.aux_keywords || [];
        formData.category = detail.category || "";
        formData.tags = detail.tags || [];
        formData.priority_level = detail.priority_level || "medium";
        formData.responsible_department = detail.responsible_department || "";
        formData.default_action = detail.default_action || "review";
        formData.config = {
          auto_cleanup: detail.config?.auto_cleanup ?? false,
          retention_days: detail.config?.retention_days ?? 60,
          cache_enabled: detail.config?.cache_enabled ?? true,
          max_results: detail.config?.max_results ?? 500,
          search_timeout: detail.config?.search_timeout ?? 180,
        };
      } else {
        // 新增模式：重置表单
        resetForm();
      }
    }
  }
);

// 重置表单
const resetForm = () => {
  formData.scene_name = "";
  formData.description = "";
  formData.main_keywords = [];
  formData.aux_keywords = [];
  formData.category = "";
  formData.tags = [];
  formData.priority_level = "medium";
  formData.responsible_department = "";
  formData.default_action = "review";
  formData.config = {
    auto_cleanup: false,
    retention_days: 60,
    cache_enabled: true,
    max_results: 500,
    search_timeout: 180,
  };
  formRef.value?.clearValidate();
};

// 弹窗关闭时重置表单
const handleClosed = () => {
  resetForm();
  // 清空关键词缓存，下次打开时重新加载
  keywordCache.value.clear();
  keywordOptions.value = [];
};

// 取消
const handleCancel = () => {
  emit("update:modelValue", false);
};

// 保存
const handleSave = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    saving.value = true;

    // 构建提交数据
    const submitData: any = {
      scene_name: formData.scene_name,
      main_keywords: formData.main_keywords,
    };

    // 可选字段
    if (formData.description) {
      submitData.description = formData.description;
    }
    if (formData.aux_keywords && formData.aux_keywords.length > 0) {
      submitData.aux_keywords = formData.aux_keywords;
    }
    if (formData.category) {
      submitData.category = formData.category;
    }
    if (formData.tags && formData.tags.length > 0) {
      submitData.tags = formData.tags;
    }
    if (formData.priority_level) {
      submitData.priority_level = formData.priority_level;
    }
    if (formData.responsible_department) {
      submitData.responsible_department = formData.responsible_department;
    }
    if (formData.default_action) {
      submitData.default_action = formData.default_action;
    }

    // 配置对象（只包含有值的字段）
    const config: any = {};
    if (formData.config.auto_cleanup !== undefined) {
      config.auto_cleanup = formData.config.auto_cleanup;
    }
    if (formData.config.retention_days) {
      config.retention_days = formData.config.retention_days;
    }
    if (formData.config.cache_enabled !== undefined) {
      config.cache_enabled = formData.config.cache_enabled;
    }
    if (formData.config.max_results) {
      config.max_results = formData.config.max_results;
    }
    if (formData.config.search_timeout) {
      config.search_timeout = formData.config.search_timeout;
    }

    if (Object.keys(config).length > 0) {
      submitData.config = config;
    }

    emit("save", submitData);
  } catch (error) {
    console.error("表单验证失败:", error);
  } finally {
    saving.value = false;
  }
};
</script>

<style scoped lang="scss">
.scene-form {
  max-height: 70vh;
  overflow-y: auto;
  padding-right: 10px;

  .form-hint {
    font-size: 12px;
    color: #909399;
    margin-top: 4px;
    line-height: 1.5;
  }

  :deep(.el-divider__text) {
    font-size: 14px;
    font-weight: 500;
    color: #303133;
  }
}
</style>
